<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import { MY_STATE } from '$lib/api/proto/roadmap_member_api';
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import UserLogin from '$lib/components/user/UserLogin.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { ChevronsLeft } from 'lucide-svelte';

	const roadmapId = page.url.searchParams.get('roadmapId') ?? '';

	let { children } = $props();

	let showPlanTab = $state(false);

	let myState = $state(null as MY_STATE | null);
	let showLogin = $state(false);

	async function checkShowPlanTab() {
		if (userStore.userSession == null || userStore.userInfo == null) {
			return;
		}
		if (
			userStore.userInfo.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH &&
			myState == MY_STATE.MY_STATE_IS_OWNER
		) {
			const res = await callApi(
				appStore.roadmapMemberApiClient.listMember({
					sessionId: userStore.userSession,
					roadmapId: roadmapId,
					offset: 0,
					limit: 1
				}).response
			);
			if (res.totalCount > 0) {
				showPlanTab = true;
			}
		} else if (
			userStore.userInfo.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT &&
			myState == MY_STATE.MY_STATE_IS_MEMBER
		) {
			const res = await callApi(
				appStore.roadmapPlanApiClient.listPlan({
					sessionId: userStore.userSession,
					roadmapId: roadmapId,
					targetMemberUserId: userStore.userInfo.userId
				}).response
			);
			if (res.planList.length > 0) {
				showPlanTab = true;
			}
		}
	}

	async function loadMyState() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapMemberApiClient.getMyState({
				sessionId: userStore.userSession,
				roadmapId: roadmapId
			}).response
		);
		myState = res.myState;
	}

	async function applyJoin() {
		if (userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.roadmapMemberApiClient.applyJoin({
				sessionId: userStore.userSession,
				roadmapId: roadmapId
			}).response
		);
		await loadMyState();
		appStore.addToastMessage({
			level: 'success',
			content: '申请访问成功',
			keepTime: 2000
		});
	}

	$effect(() => {
		checkShowPlanTab();
	});

	$effect(() => {
		loadMyState();
	});
</script>

{#if userStore.userSession == null}
	<div class="flex justify-center mt-[100px]">
		<div class="flex items-center justify-center">
			<p>
				您还未登录！请
				<button type="button" class="btn btn-primary ml-[20px]" onclick={() => (showLogin = true)}
					>登录</button
				>
			</p>
		</div>
	</div>
{:else if myState == MY_STATE.MY_STATE_IN_APPLY}
	<div class="flex justify-center mt-[100px]">等待成长路线图管理员通过申请！</div>
{:else if myState == MY_STATE.MY_STATE_CAN_APPLY}
	<div class="flex justify-center mt-[100px]">
		<div class="flex items-center justify-center">
			<p>您还没有访问权限！</p>
			<button type="button" class="btn btn-primary ml-[20px]" onclick={() => applyJoin()}
				>申请访问</button
			>
		</div>
	</div>
{:else if myState == MY_STATE.MY_STATE_NO_PERM}
	<div class="flex justify-center mt-[100px] text-error">
		<p>没有权限</p>
	</div>
{:else if myState == MY_STATE.MY_STATE_IS_MEMBER || myState == MY_STATE.MY_STATE_IS_OWNER}
	<div role="tablist" class="tabs tabs-lift p-1">
		<button type="button" class="btn btn-ghost" onclick={() => goto('/app')}>
			<ChevronsLeft size="32" />
		</button>
		<button
			role="tab"
			class="tab {page.url.pathname.startsWith('/app/roadmap/map') ? 'tab-active' : ''} mb-[8px]"
			onclick={() => (window.location.href = `/app/roadmap/map?roadmapId=${encodeURI(roadmapId)}`)}
			>成长路线图</button
		>
		{#if showPlanTab}
			<button
				role="tab"
				class="tab {page.url.pathname.startsWith('/app/roadmap/plan') ? 'tab-active' : ''} mb-[8px]"
				onclick={() =>
					(window.location.href = `/app/roadmap/plan?roadmapId=${encodeURI(roadmapId)}`)}
				>成长计划</button
			>
		{/if}
		<button
			role="tab"
			class="tab {page.url.pathname.startsWith('/app/roadmap/qa') ? 'tab-active' : ''} "
			onclick={() => (window.location.href = `/app/roadmap/qa?roadmapId=${encodeURI(roadmapId)}`)}
			>问答专区</button
		>

		{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH}
			<button
				role="tab"
				class="tab {page.url.pathname.startsWith('/app/roadmap/setting') ? 'tab-active' : ''} "
				onclick={() =>
					(window.location.href = `/app/roadmap/setting?roadmapId=${encodeURI(roadmapId)}`)}
				>设置</button
			>
		{/if}
	</div>

	<div class="relative">
		{@render children()}
	</div>
{/if}

<div class="absolute -left-[10000px]">
	{#if showLogin}
		<UserLogin onClose={() => (showLogin = false)} />
	{/if}
</div>
